<template>
  <el-card>
    <div slot="header">
      <h3>SPU图片</h3>
    </div>
    <div class="image_wrap">
      <el-divider content-position="right">
        <template v-if="isEditPage">
          <el-button
            type="text"
            @click="handleSubmitOrEdit"
            :loading="btnLoading.submit"
          >修改</el-button>
        </template>
        <template v-if="isAddPage">
          <el-button
            type="text"
            @click="handleSave"
            :loading="btnLoading.submit"
          >保存</el-button>
          <el-button
            type="text"
            @click="handleSubmitOrEdit"
            :loading="btnLoading.submit"
          >提交</el-button>
          <el-button
            type="text"
            @click="handleBack"
          >返回</el-button>
        </template>
      </el-divider>
      <el-form ref="formData" :model="formData" :rules="formRules" label-width="180px">
        <el-form-item label="商品主图片（未精修）" prop="mainImage">
          <Upload
            :readOnly="isViewPage"
            :maxLen="1"
            :defaultList="echoImages.mainImage"
            :format="['jpg', 'jpeg', 'png']"
            @handleChangeImage="files => { setImageListByType('mainImage', files) }"
          />
        </el-form-item>
        <el-form-item label="商品主图片（精修）" prop="mainImageTrimming">
          <Upload
            :readOnly="isViewPage"
            :maxLen="1"
            :defaultList="echoImages.mainImageTrimming"
            :format="['jpg', 'jpeg', 'png']"
            @handleChangeImage="files => { setImageListByType('mainImageTrimming', files) }"
          />
        </el-form-item>
        <el-form-item label="商品多角度图（未精修）" prop="multiImage">
          <Upload
            :readOnly="isViewPage"
            :showTip="true"
            :isMultiple="true"
            :defaultList="echoImages.multiImage"
            :maxLen="5"
            :format="['jpg', 'jpeg', 'png']"
            @handleChangeImage="files => { setImageListByType('multiImage', files) }"
          />
        </el-form-item>
        <el-form-item label="商品多角度图（精修）" prop="multiImageTrimming">
          <Upload
            :readOnly="isViewPage"
            :showTip="true"
            :isMultiple="true"
            :defaultList="echoImages.multiImageTrimming"
            :maxLen="5"
            :format="['jpg', 'jpeg', 'png']"
            @handleChangeImage="files => { setImageListByType('multiImageTrimming', files) }"
          />
        </el-form-item>
        <el-card shadow="never">
          <div slot="header">
            <span class="error_color">*</span>
            <span>详情信息</span>
          </div>
          <IQuill v-model="formData.imageDescribe" />
        </el-card>
      </el-form>
    </div>
  </el-card>
</template>
<script>
import UploadImages from '../components/UploadImages';
import Upload from '@/components/common/upload'; // 上传组件
import IQuill from '@/components/quill'; // 编辑器组件
import {
  queryImageInfoService,
  submitImageInfoService
} from '@/api/commodity/temporaryPurchasingGoods/temporaryProjectGoods';
import { removeSessionByRoute } from '@/utils/bizUtils';
export default {
  components: { UploadImages, Upload, IQuill },
  data () {
    return {
      formData: {
        mainImage: [], // 商品主图片（未精修）
        mainImageTrimming: [], // 商品主图片（精修）
        multiImage: [], // 商品多角度图（未精修）
        multiImageTrimming: [], // 商品多角度图（精修）
        imageDescribe: '', // 详情信息
        imageDescribeUuid: '' // 详情信息uuid，后端生成，有值就传
      },
      formRules: {
        mainImageTrimming: { required: true, message: '商品主图片（精修）不能为空' },
        multiImageTrimming: { required: true, message: '商品多角度图（精修）不能为空' }
      },
      btnLoading: {
        submit: false
      },
      // 回显图片实例，套用formData会出现组件数据错乱问题
      echoImages: {
        mainImage: [], // 商品主图片（未精修）
        mainImageTrimming: [], // 商品主图片（精修）
        multiImage: [], // 商品多角度图（未精修）
        multiImageTrimming: [], // 商品多角度图（精修）
      }
    }
  },
  computed: {
    isViewPage () {
      return this.$route.query.type == 'view'
    },
    isEditPage () {
      return this.$route.query.type == 'edit';
    },
    isAddPage () {
      return !this.$route.query.type
    },
    // 图片为空（精修或非精修图至少上传1张）
    hasNoImages () {
      const checkNames = ['mainImage', 'mainImageTrimming', 'multiImage', 'multiImageTrimming'];
      const isEmpty = checkNames.every(item => this.formData[item].length === 0);
      return isEmpty;
    }
  },
  mounted () {
    this.getHistoryImageInfo();
  },
  beforeRouteLeave (to, from, next) {
    removeSessionByRoute({
      toName: to.name,
      notRemoveNames: this.$route.query?.fromName,
      cacheKey: this.$route.query?.cacheKey
    })
    next();
  },
  methods: {
    // 根据类型设置图片集合
    setImageListByType (typeName, files) {
      this.formData[typeName] = files;
      this.echoImages[typeName] = files;
    },
    // 设置回显图片数据集合
    setEchoImageList (typeName, files) {
      if (!files) return false;
      if (typeof files === 'string') {
        // this.echoImages[typeName] = [files];
        this.echoImages[typeName] = [{ url: files }]
      } else {
        // this.echoImages[typeName] = files;
        this.echoImages[typeName] = files.map(item => ({ url: item }))
      }
    },
    // 获取图片提交入参
    getImagesParams () {
      const multiImageList = this.getMultiImageList(this.formData.multiImage, 'noTrimming');
      const multiImageTrimmingList = this.getMultiImageList(this.formData.multiImageTrimming, 'trimming');
      const multiImage = [...multiImageList, ...multiImageTrimmingList]
        .map(item => ({ ...item, imageKey: item?.imageKey?.url ?? '' }))
        .filter(item => item)
      return {
        mainImage: this.formData.mainImage[0]?.url,
        mainImageTrimming: this.formData.mainImageTrimming[0]?.url,
        multiImage,
        imageDescribe: this.formData.imageDescribe,
        imageDescribeUuid: this.formData.imageDescribeUuid
      }
    },
    // 获取多角度图片集合
    getMultiImageList (list, type, isFilter) {
      if (!list || list.length === 0) return [];
      const multiImageTypes = {
        trimming: '0', // 0是精修
        noTrimming: '1' // 1是非精修
      }
      if (isFilter) {
        const filterList = list
          .filter(item => item.trimming == multiImageTypes[type])
          .map(item => item.imageKey);
        return filterList;
      }
      const multiImages = list.map((item, index) => ({
        trimming: multiImageTypes[type],
        position: index,
        imageKey: item
      }))
      return multiImages;
    },
    // 保存
    handleSave () {
      this.setEchoToFormData();
      const message = '请至少上传1张精修或非精修图再进行保存';
      if (this.hasNoImages) return this.$message.warning(message);
      this.submitOrSaveImages('1');
    },
    // 提交
    handleSubmitOrEdit () {
      this.setEchoToFormData();
      this.submitOrSaveImages('2')
      // this.validateImgTextInfo();
    },
    // 设置回显值给表单数据
    setEchoToFormData () {
      for (const key in this.echoImages) {
        if (this.echoImages[key] && this.echoImages[key].length !== 0) {
          this.formData[key] = this.echoImages[key];
        }
      }
    },
    // 必填校验
    // validateImgTextInfo () {
    //   this.setEchoToFormData();
    //   this.$refs.formData.validate((valid) => {
    //     if (valid) {
    //       if (!this.formData.imageDescribe) return this.$message.warning('详情信息不能为空');
    //       this.submitOrSaveImages('2')
    //     } else {
    //       console.log(this.formData);
    //       this.$message.warning('必填项不能为空');
    //     }
    //   });
    // },
    // 提交或保存图文信息
    async submitOrSaveImages (saveOrSubmit) {
      const loadingFn = state => { this.btnLoading.submit = state };
      const { skuId, skuNo, productType } = this.$route.query;
      const data = {
        skuId,
        skuNo,
        saveOrSubmit,
        productType,
        ...this.getImagesParams()
      }
      const res = await submitImageInfoService(data, loadingFn)
      if (!res) return false;
      this.btnLoading.submit = true; // 启用loading防止延时期间再次点击
      const message = `${saveOrSubmit == '1' ? '保存' : '提交'}成功`;
      this.$message.success(message);
      setTimeout(() => {
        if (this.isAddPage) this.$router.go(-1);
        else window.close();
      }, 1000);
    },
    // 获取历史图片信息
    async getHistoryImageInfo () {
      if (!this.$route.query) return false;
      const { skuId, skuNo } = this.$route.query;
      const data = { skuId, skuNo };
      const retData = await queryImageInfoService(data, '.image_wrap');
      const { mainImage, mainImageTrimming, multiImage, imageDescribe, imageDescribeUuid } = retData;
      const multiImageList = this.getMultiImageList(multiImage, 'noTrimming', true);
      const multiImageTrimming = this.getMultiImageList(multiImage, 'trimming', true);
      this.setEchoImageList('mainImage', mainImage);
      this.setEchoImageList('mainImageTrimming', mainImageTrimming);
      this.setEchoImageList('multiImage', multiImageList);
      this.setEchoImageList('multiImageTrimming', multiImageTrimming);
      this.formData.imageDescribe = imageDescribe;
      this.formData.imageDescribeUuid = imageDescribeUuid;
    },
    // 返回
    handleBack () {
      this.$router.go(-1)
    }
  }
}
</script>
<style lang="less" scoped>
  /deep/ .i-quill {
    height: 100%;
  }
</style>
